package com.github.cyf.captcha;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * @author chenyifan
 * @create 2024-04-29 19:03
 */
@Api(tags = "验证码模块")
@Controller
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/getCode1")
    @ApiOperation("获取中文动态验证码")
    public void getCode() throws IOException {
        response.setContentType(MimeTypeUtils.IMAGE_GIF_VALUE);
        // 中文动态验证码
        ChineseGifCaptcha captcha = new ChineseGifCaptcha(120, 40);
        captcha.setLen(4);
        captcha.out(response.getOutputStream());
        // 获取运算结果
        log.info(captcha.text());
    }

    @GetMapping("/getCode2")
    @ApiOperation("获取运算验证码")
    public void getCode2() throws IOException {
        response.setContentType(MimeTypeUtils.IMAGE_GIF_VALUE);
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        String arithmetic = captcha.getArithmeticString();// 获取运算的公式：3+2=?
        String verCode = captcha.text().toLowerCase(); // 获取运算的结果：5
        captcha.out(response.getOutputStream());
        log.info("运算公式:{}, 结果:{}", arithmetic, verCode);
    }

    @GetMapping("/getCode3")
    @ApiOperation("获取纯数字验证码")
    public void getCode3() throws IOException {
        response.setContentType(MimeTypeUtils.IMAGE_GIF_VALUE);
        // 三个参数分别为宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
        // 设置字体
        captcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        // 输出图片流
        captcha.out(response.getOutputStream());
        log.info(captcha.text());
    }

}
